import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
 
/**
 * 使用meta.role确定当前用户是否具有权限
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}
 
/**
 * 后台查询的菜单数据拼装成路由格式的数据
 * @param routes
 */
export function generaMenu(routes, data) {
  data.forEach(item => {
    const menu = {
      path: item.menuUrl === '#' ? item.menuCode + '_key' : item.menuUrl,
      component: item.menuUrl === '#' ? Layout : () => import(`@/views${item.menuUrl}/index`),
      // hidden: true,
      children: [],
      name: 'menu_' + item.menuCode,
      meta: { title: item.menuName, id: item.menuCode, roles: ['admin'] }
    }
    if (item.children) {
      generaMenu(menu.children, item.children)
    }
    routes.push(menu)
  })
}
 
/**
 * 通过递归过滤异步路由表
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (tmp.children) {
      tmp.children = filterAsyncRoutes(tmp.children, roles)
    }
    res.push(tmp)
  })
  return res
}
 
const state = {
  routes: [],
  addRoutes: []
}
 
const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}
 
const actions = {
  generateRoutes({ commit }, menudata) {
    return new Promise(resolve => {
      const loadMenuData = []
      let data = menudata
      Object.assign(loadMenuData, data)
      generaMenu(asyncRoutes, loadMenuData)
      console.log(asyncRoutes)
      let accessedRoutes
      accessedRoutes = filterAsyncRoutes(asyncRoutes, menudata)
      console.log(accessedRoutes)
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}
 
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
